package com.dlc.apk.utils

import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager

class PrefUtil {
    var sp: SharedPreferences
        private set

    private constructor(preferences: SharedPreferences) {
        sp = preferences
    }

    private constructor(context: Context, name: String) {
        sp = context.getSharedPreferences(name, 0)
    }

    fun edit(): SharedPreferences.Editor {
        return sp.edit()
    }

    fun putInt(key: String?, value: Int): SharedPreferences.Editor {
        return edit().putInt(key, value)
    }

    fun saveInt(key: String?, value: Int) {
        putInt(key, value).apply()
    }

    fun getInt(key: String?, defValue: Int): Int {
        return sp.getInt(key, defValue)
    }

    fun putFloat(key: String?, value: Float): SharedPreferences.Editor {
        return edit().putFloat(key, value)
    }

    fun saveFloat(key: String?, value: Float) {
        putFloat(key, value).apply()
    }

    fun getFloat(key: String?, defValue: Float): Float {
        return sp.getFloat(key, defValue)
    }

    fun putBoolean(key: String?, value: Boolean): SharedPreferences.Editor {
        return edit().putBoolean(key, value)
    }

    fun saveBoolean(key: String?, value: Boolean) {
        putBoolean(key, value).apply()
    }

    fun getBoolean(key: String?, defValue: Boolean): Boolean {
        return sp.getBoolean(key, defValue)
    }

    fun putLong(key: String?, value: Long): SharedPreferences.Editor {
        return edit().putLong(key, value)
    }

    fun saveLong(key: String?, value: Long) {
        putLong(key, value).apply()
    }

    fun getLong(key: String?, defValue: Long): Long {
        return sp.getLong(key, defValue)
    }

    fun putString(key: String?, value: String?): SharedPreferences.Editor {
        return edit().putString(key, value)
    }

    fun saveString(key: String?, value: String?) {
        putString(key, value).apply()
    }

    fun getString(key: String?, defValue: String?): String? {
        return sp.getString(key, defValue)
    }

    companion object {
        private var sDefault: PrefUtil? = null
        @JvmStatic
        fun init(context: Context) {
            sDefault = PrefUtil(PreferenceManager.getDefaultSharedPreferences(context.applicationContext))
        }

        @JvmStatic
        val default: PrefUtil?
            get() {
                checkInit()
                return sDefault
            }

        fun newInstance(context: Context, name: String): PrefUtil {
            return PrefUtil(context, name)
        }

        private fun checkInit() {
            if (sDefault == null) {
                throw NullPointerException("默认PrefUtil为null，请先调用PrefUtil.init(context)进行初始化")
            }
        }
    }
}